package com.mj.attribution.activity;

import java.util.Timer;
import java.util.TimerTask;

import com.mj.attribution.R;
import com.mj.attribution.bean.ShowjiJSON;
import com.mj.attribution.service.PhoneNumberService;
import com.mj.attribution.util.NetUtils;
import com.mj.attribution.util.RegUtil;
import com.qq.e.ads.appwall.APPWall;
import com.qq.e.ads.banner.ADSize;
import com.qq.e.ads.banner.AbstractBannerADListener;
import com.qq.e.ads.banner.BannerView;
import com.qq.e.ads.interstitial.AbstractInterstitialADListener;
import com.qq.e.ads.interstitial.InterstitialAD;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 手机号码归属地
 * @author zhaominglei
 * @date 2015-3-10
 * 
 */
public class MainActivity extends Activity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = MainActivity.class.getSimpleName();
	private static final String APPID = "1104352344";
	private static final String BannerPosID = "1050904555520977";//Banner
	private static final String APPWallPosID = "2080902545028908";//APPWall
	private static final String InterteristalPosID = "3040104565228919";//InterteristalPos
	private PhoneNumberService phoneNumberService = new PhoneNumberService();
	private boolean isExit = false;
	private TimerTask timerTask;
	private LinearLayout miniAdLinearLayout; //迷你广告
	private EditText phoneNumberText; //手机号码输入框
	private String phoneNumber; //手机号码 
	private Button queryBtnButton; //查询
	private ProgressBar queryProgressBar; // 查询进度条
	private TextView resultView;
	private Button appOffersButton; //推荐应用
	private BannerView bv;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		init();
	}

	private void init() {
		miniAdLinearLayout = (LinearLayout)findViewById(R.id.miniAdLinearLayout);
		phoneNumberText = (EditText)findViewById(R.id.attribution_phonenumber_edt);
		queryBtnButton = (Button)findViewById(R.id.attribution_query_btn);
		queryProgressBar = (ProgressBar)findViewById(R.id.attribution_query_progressbar);
		resultView = (TextView)findViewById(R.id.attribution_result);
		appOffersButton = (Button)findViewById(R.id.appOffersButton);
		
		queryBtnButton.setOnClickListener(this);
		appOffersButton.setOnClickListener(this);

		bv = new BannerView(this, ADSize.BANNER, APPID, BannerPosID);
	    bv.setRefresh(30);
	    bv.setADListener(new AbstractBannerADListener() {
	      @Override
	      public void onNoAD(int arg0) {
	        Log.i("AD_DEMO", "BannerNoAD，eCode=" + arg0);
	      }
	      @Override
	      public void onADReceiv() {
	        Log.i("AD_DEMO", "ONBannerReceive");
	      }
	    });
	    miniAdLinearLayout.addView(bv);
	    bv.loadAD();
	    final InterstitialAD iad = new InterstitialAD(this, APPID, InterteristalPosID);
	    iad.setADListener(new AbstractInterstitialADListener() {
	      @Override
	      public void onNoAD(int arg0) {
	        Log.i("AD_DEMO", "LoadInterstitialAd Fail:" + arg0);
	      }
	      @Override
	      public void onADReceive() {
	        iad.show();
	      }
	    });
	    iad.loadAD();
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.attribution_query_btn:
			resultView.setText("");
			phoneNumber = phoneNumberText.getText().toString();
			if (phoneNumber == null || phoneNumber.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.attribution_phonenumber_hint, Toast.LENGTH_SHORT).show();
				return;
			}
			if (!RegUtil.isMobile(phoneNumber)) {
				Toast.makeText(getApplicationContext(), R.string.attribution_error1, Toast.LENGTH_SHORT).show();
				return;
			}
			getAttribution();
			break;
			
		case R.id.appOffersButton:
			APPWall wall = new APPWall(this, APPID, APPWallPosID);
	        wall.setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	        wall.doShowAppWall();
			break;

		default:
			break;
		}
	}
	
	private void getAttribution() {
		if (NetUtils.isConnected(getApplicationContext())) {
			queryProgressBar.setVisibility(View.VISIBLE);
			new AttributionAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isExit) {
			MainActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}
	
	public class AttributionAsyncTask extends AsyncTask<String, String, ShowjiJSON> {

		@Override
		protected ShowjiJSON doInBackground(String... params) {
			return phoneNumberService.getAttribution(phoneNumber);
		}

		@Override
		protected void onPostExecute(ShowjiJSON result) {
			queryProgressBar.setVisibility(View.GONE);
			if (result != null) {
				if ("True".equals(result.getQueryResult())) {
					StringBuilder sb = new StringBuilder();
					sb.append("所查号码:").append("    ").append(result.getMobile()).append("\n\n");
					sb.append("归属省份:").append("    ").append(result.getProvince()).append("\n\n");
					sb.append("归属城市:").append("    ").append(result.getCity()).append("\n\n");
					sb.append("城市区号:").append("    ").append(result.getAreaCode()).append("\n\n");
					sb.append("城市邮编:").append("    ").append(result.getPostCode()).append("\n\n");
					sb.append("运营商:").append("    ").append(result.getVno()).append(result.getTo()).append("\n\n");
					resultView.setText(sb.toString());
				} else {
					Toast.makeText(getApplicationContext(), R.string.attribution_error2, Toast.LENGTH_SHORT).show();
				}
			}
		}
	}
}
